package cn.com.blueInfo.bpm.template.repository.impl;

import cn.com.blueInfo.bpm.common.entity.BaseEntity;
import cn.com.blueInfo.bpm.common.enums.BaseDeleted;
import cn.com.blueInfo.bpm.common.repository.BaseRepository;
import cn.com.blueInfo.bpm.template.entity.AutomationRule;
import cn.com.blueInfo.bpm.template.enums.AutomationRuleExecutionType;
import cn.com.blueInfo.bpm.template.mapper.AutomationRuleMapper;
import cn.com.blueInfo.bpm.template.repository.AutomationRuleRepository;
import cn.com.blueInfo.bpm.template.request.AutomationRuleDTO;
import cn.com.blueInfo.core.entity.CurrentLoginUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自动化规则表 数据服务实现类
 * @author suxch
 * @since 2025-09-01 19:30:44
 */
@Log4j2
@Service
public class AutomationRuleRepositoryImpl
        extends ServiceImpl<AutomationRuleMapper, AutomationRule>
        implements AutomationRuleRepository, BaseRepository<AutomationRule, AutomationRuleDTO.QueryDTO> {

    @Autowired
    private CurrentLoginUserInfo currentLoginUserInfo;

    /**
     * 提供获取 CurrentLoginUserInfo 的方法（由实现类提供，避免接口中注入）
     * @return CurrentLoginUserInfo
     */
    @Override
    public CurrentLoginUserInfo getCurrentLoginUserInfo() {
        return currentLoginUserInfo;
    }

    /**
     * 新增自动化规则
     * @param automationRule 自动化规则参数
     */
    @Override
    public Integer createAutomationRule(AutomationRule automationRule) {
        return sqlExecuteResult(save(automationRule));
    }

    /**
     * 批量新增自动化规则
     * @param automationRuleList 自动化规则参数列表
     */
    @Override
    public Integer batchCreateAutomationRule(List<AutomationRule> automationRuleList) {
        return sqlExecuteResult(saveBatch(automationRuleList), automationRuleList.size());
    }

    /**
     * 删除自动化规则
     * @param automationRuleId 自动化规则ID
     */
    @Override
    public Integer deleteAutomationRule(Long automationRuleId) {
        AutomationRule automationRule = new AutomationRule();
        automationRule.setId(automationRuleId);
        automationRule.setDeleted(BaseDeleted.DELETED);
        return sqlExecuteResult(removeById(automationRule));
    }

    /**
     * 批量删除自动化规则
     * @param automationRuleIdList 自动化规则ID列表
     */
    @Override
    public Integer batchDeleteAutomationRule(List<Long> automationRuleIdList) {
        List<AutomationRule> automationRuleList = new ArrayList<>();
        for (Long automationRuleId : automationRuleIdList) {
            AutomationRule automationRule = new AutomationRule();
            automationRule.setId(automationRuleId);
            automationRule.setDeleted(BaseDeleted.DELETED);
            automationRuleList.add(automationRule);
        }
        return sqlExecuteResult(removeBatchByIds(automationRuleList), automationRuleList.size());
    }

    /**
     * 更新部分自动化规则
     * @param automationRule 自动化规则参数
     */
    @Override
    public Integer updateAutomationRulePartial(AutomationRule automationRule) {
        validateUpdateId(automationRule.getId());
        LambdaUpdateWrapper<AutomationRule> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AutomationRule::getId, automationRule.getId());
        return sqlExecuteResult(update(updateWrapper));
    }

    /**
     * 更新全部自动化规则
     * @param automationRule 自动化规则参数
     */
    @Override
    public Integer updateAutomationRule(AutomationRule automationRule) {
        validateUpdateId(automationRule.getId());
        return sqlExecuteResult(updateById(automationRule));
    }

    /**
     * 查询一条自动化规则
     * @param automationRuleId 自动化规则ID
     */
    @Override
    public AutomationRule getAutomationRuleById(Long automationRuleId) {
        LambdaQueryWrapper<AutomationRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AutomationRule::getId, automationRuleId);
        return getOne(queryWrapper);
    }

    /**
     * 分页查询自动化规则
     * @param automationRuleQueryDTO 自动化规则参数
     */
    @Override
    public Page<AutomationRule> getAutomationRulePage(AutomationRuleDTO.QueryDTO automationRuleQueryDTO) {
        Page<AutomationRule> automationRulePage = new Page<>(
                automationRuleQueryDTO.getPage(), automationRuleQueryDTO.getSize());
        LambdaQueryWrapper<AutomationRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, automationRuleQueryDTO);

        BaseDeleted deleted = automationRuleQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeletePage(automationRulePage, queryWrapper);
        } else {
            return page(automationRulePage, queryWrapper);
        }
    }

    /**
     * 根据条件查询 自动化规则 数量
     * @param automationRuleQueryDTO 自动化规则参数
     */
    @Override
    public Long getAutomationRuleCount(AutomationRuleDTO.QueryDTO automationRuleQueryDTO) {
        LambdaQueryWrapper<AutomationRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, automationRuleQueryDTO);

        BaseDeleted deleted = automationRuleQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteCount(queryWrapper);
        } else {
            return count(queryWrapper);
        }
    }

    /**
     * 根据条件查询 自动化规则
     * @param automationRuleQueryDTO 自动化规则参数
     */
    @Override
    public List<AutomationRule> getAutomationRuleList(AutomationRuleDTO.QueryDTO automationRuleQueryDTO) {
        LambdaQueryWrapper<AutomationRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, automationRuleQueryDTO);

        BaseDeleted deleted = automationRuleQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteList(queryWrapper);
        } else {
            return list(queryWrapper);
        }
    }

    private void queryWrapper(LambdaQueryWrapper<AutomationRule> queryWrapper,
                              AutomationRuleDTO.QueryDTO automationRuleQueryDTO) {

        Long processId = automationRuleQueryDTO.getProcessId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(processId), AutomationRule::getProcessId, processId);

        Long nodeId = automationRuleQueryDTO.getNodeId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(nodeId), AutomationRule::getNodeId, nodeId);

        String ruleCode = automationRuleQueryDTO.getRuleCode();
        queryWrapper.eq(StringUtils.isNotBlank(ruleCode), AutomationRule::getRuleCode, ruleCode);

        String ruleName = automationRuleQueryDTO.getRuleName();
        queryWrapper.eq(StringUtils.isNotBlank(ruleName), AutomationRule::getRuleName, ruleName);

        String conditionExpr = automationRuleQueryDTO.getConditionExpr();
        queryWrapper.eq(StringUtils.isNotBlank(conditionExpr), AutomationRule::getConditionExpr, conditionExpr);

        AutomationRuleExecutionType executionType = automationRuleQueryDTO.getExecutionType();
        queryWrapper.eq(ObjectUtils.isNotEmpty(executionType), AutomationRule::getExecutionType, executionType);

        String executionParam = automationRuleQueryDTO.getExecutionParam();
        queryWrapper.eq(StringUtils.isNotBlank(executionParam), AutomationRule::getExecutionParam, executionParam);

        addQueryWrapper(queryWrapper, automationRuleQueryDTO, getCommonColumn());

    }

    private Map<String, SFunction<AutomationRule, ?>> getCommonColumn() {
        return BaseEntity.getCommonColumn(
                AutomationRule::getOrderNumber,
                AutomationRule::getTenantId,
                AutomationRule::getApplicationId,
                AutomationRule::getStatus,
                AutomationRule::getDeleted,
                AutomationRule::getDeleteUserId,
                AutomationRule::getDeleteTime,
                AutomationRule::getRemark,
                AutomationRule::getCreateUserId,
                AutomationRule::getCreateTime,
                AutomationRule::getUpdateUserId,
                AutomationRule::getUpdateTime,
                AutomationRule::getExtend1,
                AutomationRule::getExtend2,
                AutomationRule::getExtend3);
    }

}
